from django.shortcuts import render
from django.views.generic import View
from .models import TicketConf,Seven_star_ticket
from django.http import JsonResponse
import requests
import json
import pandas
import logging
logger = logging.getLogger(__name__)
from datetime import datetime
# Create your views here.

class SyncData(View):
    def get(self,request):
        # read conf url
        logger.info("start get")
        tc_list = TicketConf.objects.filter(status=True)
        results={}
        for tc in tc_list:
            results[tc.name] = sync_map.get(tc.name)(tc).sync_data()
        return JsonResponse(results)

class QXC:
    def __init__(self,qxc):
        self.qxc = qxc
        self.tc_url=qxc.url
        self.params = qxc.params

    def get_now_data(self,tc_url,kw):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
        logger.error("request kw %s",kw)
        response = requests.get(tc_url,params=kw,headers=headers)
        if response.status_code == 200:
            return response.json()
        else:
            logger.error("get %s data is failed,detail %s",tc_url,response.text)
            return None

    def get_last_store_num(self):
        qxc = Seven_star_ticket.objects.filter(data_class=0).order_by("-publish_num").first()
        if qxc:
            return qxc.publish_num
        else:
            return 0

    def sync_data(self):
        # load data from db
        # generate new data
        # request new data
        # dump data to db
        last_num=self.get_last_store_num()
        kw=json.loads(self.params)
        new_seven_star_ticket=[]
        while True:
            flag_num=False
            data = self.get_now_data(self.tc_url,kw)
            if not data:
                break
            if data.get("errorCode",'') != "0":
                break
            for qxc_item in data.get("value").get("list"):
                lottery_draw_num = int(qxc_item.get("lotteryDrawNum"))
                if lottery_draw_num <= last_num:
                    flag_num = True
                    break
                e1,e2,e3,e4,e5,e6,e7=[int(i) for i in qxc_item.get("lotteryDrawResult").split()]
                pub_date = datetime.strptime(qxc_item.get("lotteryDrawTime"),"%Y-%m-%d")
                new_seven_star_ticket.append(
                    Seven_star_ticket(name=self.qxc.name,data_class=0,publish_num=lottery_draw_num,
                                      publish_date=pub_date,e1=e1,e2=e2,e3=e3,e4=e4,e5=e5,e6=e6,e7=e7)
                )
            if flag_num:
                break
            pages = int(data.get("value").get("pages"))
            page_no = int(data.get("value").get("pageNo"))
            if page_no >= pages:
                break
            kw["pageNo"] = page_no + 1
        sst = Seven_star_ticket.objects.bulk_create(new_seven_star_ticket)
        return {"errorCode":0,"value":[str(i) for i in sst]}

class Tendency(View):
    def get(self,request):
        ticket = request.GET.get("ticket")
        probability = request.GET.get("probability")
        start = request.GET.get("start")
        end = request.GET.get("end")
        interval = request.GET.get("interval")
        if not tendency_map.get(ticket,None):
            return JsonResponse({"errorCode":1,"errorMessage":"{} not found".format(ticket)})
        if hasattr(Computer,probability):
            com = Computer(tendency_map.get(ticket),start,end,interval)
            result = getattr(com, probability)()
            print(result)
            return JsonResponse({"errorCode":0,"errorMessage":'',"value":result})
        else:
            print(probability)
            return JsonResponse({"errorCode":1,"errorMessage":"{} not found".format(probability)})

class Computer:
    def __init__(self,lottery,start,end,interval):
        self.lottery=lottery
        self.start=start
        self.end=end
        self.interval=interval
        self.data=lottery.objects.filter(data_class=0)

    def trans_pandas(self):
        dfs=[]
        for lottery in self.data:
            dfs.append(pandas.DataFrame(lottery.get_value(),index=lottery.get_index()))
        return pandas.concat(dfs)

    def line(self):
        '''
        :return:
        {"tm":["3-1","3-2","3-3"],
        "data":[{“name":"位置0","type":"line","data":[1,2,3]}
        ]}
        '''
        tm=[]
        e1={"name": "e1", "type": "line", "data":[]}
        e2={"name": "e2", "type": "line", "data": []}
        e3={"name": "e3", "type": "line", "data": []}
        e4={"name": "e4", "type": "line", "data": []}
        e5={"name": "e5", "type": "line", "data": []}
        e6={"name": "e6", "type": "line", "data": []}
        e7={"name": "e7", "type": "line", "data": []}
        self.start=datetime.strptime(self.start,"%Y-%m-%d")
        self.end=datetime.strptime(self.end,"%Y-%m-%d")
        for lottery in self.data.filter(publish_date__gt=self.start).order_by("publish_num"):
            tm.append(lottery.publish_num)
            e1["data"].append(lottery.e1)
            e2["data"].append(lottery.e2)
            e3["data"].append(lottery.e3)
            e4["data"].append(lottery.e4)
            e5["data"].append(lottery.e5)
            e6["data"].append(lottery.e6)
            e7["data"].append(lottery.e7)

        return {"tm":tm,"data":[e1,e2,e3,e4,e5,e6,e7]}


sync_map={"七星彩":QXC}
tendency_map={"七星彩":Seven_star_ticket}